from forest.resource import Resources, Resource, ValidationError

class SSHKey(Resource):
    ''' Enables/disables passwordless ssh to a machine.

        Example::

            resources:
            - $: ssh-key
              type: rsa
              key: AAAAB3NzaC1yc2EAAAA..tLETFfgZaGdwIcQhihCPyINKw4Hf+YfBYg+N6l
              host: user@hostname
              installed: false

        .. describe:: type

            Optional. Key type. (default: rsa)

        .. describe:: key

            Required. key value (String)

        .. describe:: host

            Required. Hostname this key applies for.

        .. describe:: installed

            Optional. whether to install or remove the key (Boolean). (default: true)
    '''
    __register__ = "ssh-key"

    def get_id(self):
        return 'ssh-key:'+self.get_host()

    def get_key(self):
        return self.value.get('key')

    def get_installed(self):
        return self.value.get('installed', True)

    def get_host(self):
        return self.value.get('host')

    def get_type(self):
        return 'ssh-'+self.value.get('type', 'rsa')

    def validate(self):

        valid_keys = ['type', 'key','installed', 'host']

        for k in self.value.iterkeys():
            if k not in valid_keys:
                raise ValidationError("Undefined ssh-key option %s" % k)

        if 'host' not in self.value:
            raise ValidationError("Undefined host name")

        if 'key' not in self.value:
            raise ValidationError("Undefined key")

